<template>
  <t-dialog :header="header" :visible.sync="visible" :onClose="closeDialog" :closeOnOverlayClick="false" width="80%"
    top="10%">
    <div style="height: 40vh">
      <!-- <div v-if="rowIndex == null">
        <t-alert style="margin-bottom: 20px" theme="info" :message="`当前页面可重复添加。目前已添加数量: ${data.length}`" />
      </div> -->

      <t-form ref="form" resetType="initial" :data="formData" labelWidth="160px" :rules="rules">
        <t-row style="row-gap:24px">
          <t-col :span="6">
            <t-form-item label="姓名" name="name">
              <t-select v-model="formData.name" creatable filterable @change="onLeaderNameChange" placeholder="请输入姓名"
                :loading="nameLoading" @search="remoteNameMethod" :options="nameOptions" @create="createNameOptions"
                style="width: 390px" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="性别" name="sex">
              <t-select clearable style="width:390px" :options="dict.type.sys_user_sex"
                v-model="formData.sex"></t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="身份证号" name="idCard">
              <t-input style="width: 390px" placeholder="请输入" clearable v-model="formData.idCard"></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="学位" name="degree">
              <t-select style="width: 390px" v-model="formData.degree" clearable placeholder="请选择"
                :options="dict.type.degree">
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="职务" name="duty">
              <t-input clearable style="width:390px" v-model="formData.duty"></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="平台职务" name="platformDuty">
              <t-input clearable style="width:390px" v-model="formData.platformDuty"></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="从事专业" name="majorName">
              <t-input v-model="formData.majorName" clearable placeholder="请输入专业" style="width: 390px" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="人才类型" name="personType">
              <t-select style="width:390px" v-model="formData.personType" clearable placeholder="请选择"
                :options="dict.type.kjpt_person_type"></t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="技术职称" name="profTitId">
              <t-tree-select style="width:390px" @change="onProfTitIdChange" clearable filterable
                :treeProps="{ keys: { value: 'id', label: 'name' }, valueMode: 'onlyLeaf' }"
                v-model="formData.profTitId" :data="profTitOptions" placeholder="技术职称"></t-tree-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="职称" name="profTit">
              <t-select style="width:390px" v-model="formData.profTit" clearable placeholder="请选择职称"
                :options="dict.type.prof_tit"></t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="所在单位" help="搜索不到请切换外部单位后手输" name="company">
              <t-tree-select v-if="formData.isInnerCompany === '1'" style="width:390px" clearable filterable
                :treeProps="{ keys: { value: 'label' } }" v-model="formData.company" :data="deptMenuOptions"
                placeholder="选择单位">
                <template #label>
                  <t-switch size="medium" v-model="formData.isInnerCompany" :label="['内部', '外部']"
                    :customValue="['1', '0']" @change="() => { formData.company = '' }"></t-switch>
                </template>
              </t-tree-select>
              <t-select v-else v-model="formData.company" creatable filterable placeholder="请输入"
                :loading="companyLoading" @search="remoteCompanyMethod" :options="companyOptions"
                @create="createCompanyOptions" style="width: 390px">
                <template #label>
                  <t-switch size="medium" v-model="formData.isInnerCompany" :label="['内部', '外部']"
                    :customValue="['1', '0']" @change="() => { formData.company = '' }"></t-switch>
                </template>
              </t-select>
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
    </div>
    <template #footer>
      <t-button theme="default" @click="closeDialog">取消</t-button>
      <t-button theme="primary" @click="onSubmit(1)">保存</t-button>
      <!-- <t-button theme="primary" @click="onSubmit(2)">保存并继续添加</t-button> -->
    </template>
  </t-dialog>
</template>

<script>

export default {
  props: ['header', "editOpen", "oldData", "rowIndex"],
  dicts: ["sys_user_sex", "kjpt_person_type", "prof_tit", "degree"],
  data () {
    return {
      deptMenuOptions: [],
      profTitOptions: [],
      companyLoading: false,
      companyOptions: [],
      nameLoading: false,
      nameOptions: [],
      visible: true,
      rules: {
        name: [
          {
            required: true,
            message: "姓名不能为空",
          }
        ],
        majorName: [
          {
            required: true,
            message: "从事专业不能为空",
          },
        ],
        idCard: [
          {
            required: true,
            message: "身份证号不能为空",
          },
          {
            message: "身份证号不正确",
            pattern: /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/,
          },
        ],
        sex: [
          {
            required: true,
            message: "性别不能为空",
          },
        ],
        degree: [
          {
            required: true,
            message: "学位不能为空",
          },
        ],
        platformDuty: [
          {
            required: true,
            message: "平台职务不能为空",
          }
        ],
        personType: [
          {
            required: true,
            message: "人才类型不能为空",
          }
        ],
        duty: [
          {
            required: true,
            message: "职务不能为空",
          }
        ],
        profTit: [
          {
            required: true,
            message: "职称不能为空",
          }
        ],
        profTitId: [
          {
            required: true,
            message: "技术职称不能为空",
          }
        ],
        company: [
          {
            required: true,
            message: "所在单位不能为空",
          }
        ],
        isInnerCompany: [
          {
            required: true,
            message: "不能为空",
          }
        ],
      },
      formData: {
        name: '',
        duty: '',
        profTit: '',
        profTitId: '',
        degree: '',
        idCard: '',
        sex: '',
        majorName: '',
        platformDuty: '',
        personType: '',
        company: '',
        isInnerCompany: '1'
      },
    }
  },
  watch: {
    oldData: {
      immediate: true,
      deep: true,
      handler (val) {
        Object.assign(this.formData, val)
      }
    },

  },
  created () {
    this.getProfTitTreeSelect();
    this.getDeptTreeSelect();

  },
  methods: {
    getDeptTreeSelect () {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getProfTitTreeSelect () {
      return this.$api.system.profTit.list().then(response => {
        this.profTitOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onProfTitIdChange (val, content) {
      this.formData.profTit = content.node.data.level;
    },
    createCompanyOptions (value) {
      this.companyOptions.push({
        label: `${value}`,
        value,
      });
    },
    remoteCompanyMethod (search) {
      this.companyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({ deptName: search }).then(response => {
        this.companyOptions = response.data.map(val => ({
          ...val,
          label: `${val.deptName}`,
          value: val.deptName,
        }));
        this.companyLoading = false;
      }).catch((e) => {
        this.companyLoading = false;
        this.$message.error(e.toString());
      });
    },
    onLeaderNameChange (val, content) {
      const index = this.nameOptions.findIndex(val => content.option?.id === val.id)
      this.nameOptions[index].label = this.nameOptions[index].name;
      this.$set(this.nameOptions, index, this.nameOptions[index])
      Object.assign(this.formData, content.option || this.nameOptions[index])
    },
    createNameOptions (value) {
      this.nameOptions.push({
        label: `${value}`,
        value,
        name: value
      });
    },
    remoteNameMethod (search) {
      this.nameLoading = true;
      this.$api.system.member.searchList({ name: search }).then(response => {
        this.nameOptions = response.data.map(val => ({
          ...val,
          label: `${val.name}-${val.idCard}`,
          value: `${val.name}-${val.idCard}`,
        }));
        this.nameLoading = false;
      }).catch((e) => {
        this.nameLoading = false;
        this.$message.error(e.toString());
      });
    },
    onSubmit (type) {
      // 深拷贝
      const newData = { ...this.formData };
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          if (this.editOpen) {

            this.$emit("updateMemberData", newData, this.rowIndex);
            this.$refs.form.reset();
            if (type === 1) {
              this.closeDialog()
            }
          } else {
            this.$emit("addMemberData", newData);
            this.$refs.form.reset();
            if (type === 1) {
              this.closeDialog()
            }
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
    closeDialog () {
      // this.$refs.form.reset();
      this.$emit("update:visible", false);
    },
  }
}
</script>

<style scoped></style>
